import * as classnames from 'classnames'
import _ from './lodash';
import lodash from './lodash';
import request from './request';
import config from './config';
import menu from './menu';
import Logger from './logger';
import settings from './settings';
import { CookieStorage } from './persist';
import { stateful, pure } from './tools';
import './patch';
/**
 * 数组内查询
 */
export function queryArray<T> (array: Array<T>, key: string, keyAlias: string = 'key'): T {
  const items = array.filter(item => item[keyAlias] as any as string === key);
  if (items.length) {
    return items[0];
  }
  return null;
}

/**
 * 数组格式转树状结构
 */
export function arrayToTree<T, U>(array: Array<T>, id: string = 'id', pid: string = 'pid', children = 'children'): Array<U> {
  let data = _.cloneDeep(array);
  let result = [];
  let hash = {};
  data.forEach((item, index) => {
    hash[data[index][id]] = data[index];
  })

  data.forEach((item) => {
    let hashVP = hash[item[pid]];
    if (hashVP) {
      !hashVP[children] && (hashVP[children] = []);
      hashVP[children].push(item);
    } else {
      result.push(item);
    }
  })
  return result;
}

export function getLocalStorage(key: string): string {
  if (typeof localStorage !== 'undefined') {
    return localStorage.getItem(key);
  } else {
    return '';
  }
}

export function setLocalStorage(key: string, value: string): void {
  if (typeof localStorage !== 'undefined') {
    localStorage.setItem(key, value);
  }
}

export function getDocumentProperty(...keys: Array<string>): any {
  let res = null;
  if (typeof document !== 'undefined') {
    res = document;
    for (let key of keys ) {
      res = res[key];
    }
  }
  return res;
}

/**
 * typescript支持number的枚举
 * 这里改成字符串枚举
 * @param o
 */
export function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
  return o.reduce((res, key) => {
    res[key] = key;
    return res;
  }, Object.create(null));
}

export {
  request,
  config,
  settings,
  lodash,
  classnames,
  menu,
  stateful,
  pure,
  Logger,
  CookieStorage,
 }
